﻿using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using WebApplication11.Models;
using WebApplication11.Services;
using System.Security.Cryptography;
using WebApplication11.Dao;

namespace WebApplication11.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private userService _userService = new userService();

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            if (HttpContext.Session.GetInt32("Status") == 1)
            {
                ViewBag.Status = 1;
                ViewBag.username = HttpContext.Session.GetString("user");
            }
            else
            {
                ViewBag.Status = 0;
                ViewBag.username = null;
            }
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        public IActionResult Login(user form)
        {
            HttpContext.Session.SetInt32("Login", _userService.Login(form));
            if (HttpContext.Session.GetInt32("Login") == 1)
            {
                HttpContext.Session.SetString("user", form.Username);
                HttpContext.Session.SetInt32("Status", 1);
                ViewBag.Status = 1;
                ViewBag.username = form.Username;
                return RedirectToAction("Index", "admin");
            }

            return RedirectToAction("Index");
        }

        public IActionResult Logout()
        {
            HttpContext.Session.Remove("user");
            HttpContext.Session.Remove("Status");
            return RedirectToAction("Index", "Home");
        }

        public IActionResult Register(user form)
        {
            _userService.Register(form);
            return RedirectToAction("Index", "Home");
        }
    }
}
